#include "bsondoc.h"

void BsonDoc::initid()
{
    if ( m_doc == NULL )
        return;
    
    bson_oid_t oid;
    bson_oid_init(&oid, NULL);
    BSON_APPEND_OID(m_doc, "_id", &oid);
}

void BsonDoc::setid(const string& id)
{
    if ( m_doc == NULL )
        return;

    bson_oid_t oid;
    bson_oid_init_from_string(&oid,id.c_str());
    BSON_APPEND_OID(m_doc, "_id", &oid);
}

string BsonDoc::getid(bson_t* pdoc)
{
    string strid;
    if ( pdoc == NULL )
        return strid;

    const bson_oid_t *ooid = NULL;
    BCON_EXTRACT(pdoc, "_id", BCONE_OID (ooid));
    if ( ooid != NULL )
    {
        char id[64] = {0};
        bson_oid_to_string(ooid, id);
        strid += id;
    }

    return strid;
}

string BsonDoc::toJson()
{
    string strret;
    if ( m_doc == NULL )
        return strret;

    char * str = bson_as_canonical_extended_json(m_doc, NULL);
    if ( str != NULL )
    {
        strret += str;
        //trim(strret);
        bson_free(str);
    }

    return strret;
}

string BsonDoc::toJson(bson_t* pdoc)
{
    string strret;
    if ( pdoc == NULL )
        return strret;

    char * str = bson_as_canonical_extended_json(pdoc, NULL);
    if ( str != NULL )
    {
        strret += str;
        //trim(strret);
        bson_free(str);
    }

    return strret;
}

string BsonDoc::toJson(mongoc_cursor_t *cursor)
{
    string strret;
    if ( cursor == NULL )
        return strret;

    char *str = NULL;
    const bson_t* doc = NULL;

    strret += "[";
    while (mongoc_cursor_next(cursor, &doc))
    {
        str = bson_as_json(doc, NULL);
        if ( str != NULL )
        {
            strret = strret + str + ",";
            bson_free(str);
        }
    }
    if ( strret.length() > 1 )
        strret.resize(strret.length() - 1);

    strret += "]";

    return strret;
}

string& BsonDoc::trim(string& str, const string& trimstr)
{
    size_t pos = 0;
    size_t trimlen = trimstr.length();

    pos = str.find( trimstr );
    if ( pos == string::npos )
        return str;

    string tmp;
    while ( pos != string::npos )
    {   
        if ( pos == 0 ) 
        {   
            if ( !str.empty() )
                str = str.substr(pos + 1); 

            pos = str.find(trimstr);
            continue;
        }   

        tmp += str.substr(0,pos);
        if ( str.length() - 1 == pos )
        {   
            str.clear();
            break;
        }   
        str = str.substr(pos + trimlen); 
        pos = str.find(trimstr);
    }   

    if ( !str.empty())
        tmp += str;

    str = tmp;
    return str;
};


